/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.lt.cj.core.filters;

import java.util.logging.Level;
import java.util.logging.Logger;
import org.htmlparser.Parser;
import org.htmlparser.filters.NodeClassFilter;
import org.htmlparser.lexer.Lexer;
import org.htmlparser.lexer.Page;
import org.htmlparser.tags.LinkTag;
import org.htmlparser.util.DefaultParserFeedback;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;

/*
 * @author luohong
 */
public class LinkTagCustomFilter implements ICustomFilter {

    private Parser parser;                                                      //定义解析器
    private String contentFilted;                                               //过滤后返还的内容
    private String parseText;                                                   //要解析的内容
    private String encoding;

    public LinkTagCustomFilter(String encoding) {
        this.encoding = encoding;
    }

    public String customFilt(String parseText) {

        setParseText(parseText);
        String url = "";
        try {
            NodeList list = parser.extractAllNodesThatMatch(new NodeClassFilter(LinkTag.class));
            LinkTag linkNode = (LinkTag) list.elementAt(0);
            url = linkNode.getLink();   //.getAttribute("href");
        } catch (ParserException ex) {
            Logger.getLogger(LinkTagCustomFilter.class.getName()).log(Level.SEVERE, null, ex);
        }
        return url;
    }

    private void setParseText(String parseText) {

        this.parseText = parseText;
        Lexer mLexer = new Lexer(new Page(parseText));
        parser = new Parser(mLexer, new DefaultParserFeedback(DefaultParserFeedback.QUIET));
        try {
            parser.setEncoding(encoding);
        } catch (ParserException e) {
            e.printStackTrace();
        }
    }
}
